package com.ikunikun.service.impl;

import com.ikunikun.context.BaseContext;
import com.ikunikun.dto.ShoppingCartDTO;
import com.ikunikun.entity.Dish;
import com.ikunikun.entity.Setmeal;
import com.ikunikun.entity.ShoppingCart;
import com.ikunikun.mapper.DishMapper;
import com.ikunikun.mapper.SetmealMapper;
import com.ikunikun.mapper.ShoppingCartMapper;
import com.ikunikun.service.ShoppingCartService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {

	@Resource
	private ShoppingCartMapper shoppingCartMapper;
	@Resource
	private DishMapper dishMapper;
	@Resource
	private SetmealMapper setmealMapper;

	/**
	 * 添加购物车
	 * @param shoppingCartDTO
	 */
	@Override
	public void addShoppingCart(ShoppingCartDTO shoppingCartDTO) {
		ShoppingCart shoppingCart = new ShoppingCart();
		BeanUtils.copyProperties(shoppingCartDTO, shoppingCart);
		List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);

		if (Objects.nonNull(list) && list.size() > 0){
			shoppingCart = list.get(0);
			shoppingCart.setNumber(shoppingCart.getNumber() + 1);
			shoppingCartMapper.updateNumberById(shoppingCart);
		}else {
			Long dishId = shoppingCartDTO.getDishId();
			if (dishId != null){
				// 添加菜品
				Dish dish = dishMapper.getById(dishId);
				shoppingCart.setName(dish.getName());
				shoppingCart.setImage(dish.getImage());
				shoppingCart.setAmount(dish.getPrice());
			}else {
				// 添加套餐
				Long setmealId = shoppingCartDTO.getSetmealId();
				if (Objects.nonNull(setmealId)){
					Setmeal setmeal = setmealMapper.getById(setmealId);
					shoppingCart.setName(setmeal.getName());
					shoppingCart.setImage(setmeal.getImage());
					shoppingCart.setAmount(setmeal.getPrice());
				}
			}
			shoppingCart.setUserId(BaseContext.getCurrentId());
			shoppingCart.setNumber(1);
			shoppingCart.setCreateTime(LocalDateTime.now());
			shoppingCartMapper.insert(shoppingCart);
		}
	}

	@Override
	public List<ShoppingCart> shoppingCart() {
		ShoppingCart shoppingCart = ShoppingCart.builder()
				.userId(BaseContext.getCurrentId())
				.build();

		return shoppingCartMapper.list(shoppingCart);
	}

	@Override
	public void clean() {
		shoppingCartMapper.clean(BaseContext.getCurrentId());
	}
}
